module.exports = function(app) {
	return new Handler(app);
};

var Handler = function(app) {
		this.app = app;
};

var handler = Handler.prototype;

/**
 * New client entry chat server.
 *
 * @param  {Object}   msg     request message
 * @param  {Object}   session current session object
 * @param  {Function} next    next stemp callback
 * @return {Void}
 */
handler.register = function (msg, session, next) {
	var self = this;
	var uid = msg.uid;
	var pwd = msg.pwd;
	if(uid == 'dante') {
		next(null, {
			code: 200,
			uid:uid,
			pwd:pwd
		});
		return;
	}
}
handler.login = function(msg, session, next) {
	var self = this;
	var uid = msg.uid;
	var pwd = msg.pwd;
	if(uid == 'dante') {
		next(null, {
			code: 200,
			uid:uid,
			pwd:pwd,
			msg:'Dante in connector'
		});
		return;
	}
}

handler.enter = function(msg, session, next) {
	var self = this;
	var rid = msg.rid;
	var uid = msg.username + '*' + rid
	var sessionService = self.app.get('sessionService');

	//duplicate log in
	if( !! sessionService.getByUid(uid)) { // 意义上等价于 if(x),这种写法是为了安全
		next(null, {
			code: 500,
			error: true
		});
		return;
	}

	/**
	 * session.set：给session添加一个属性，提供用户更改session的机会。
	 * session.push： session同步，在改变session之后需要同步，以后的请求处理中就可以获取最新session。
	 * session.bind(uid)就是将session与该用户id建立一个映射关系，key -- value。
	 *
	 */
	session.bind(uid);
	session.set('rid', rid);
	session.push('rid', function(err) {
		if(err) {
			console.error('set rid for session service failed! error is : %j', err.stack);//错误处理
		}
	});
	session.on('closed', onUserLeave.bind(null, self.app));//事件绑定

	//put user into channel
	self.app.rpc.chat.chatRemote.add(session, uid, self.app.get('serverId'), rid, true, function(users){
		next(null, {
			users:users
		});
	});
};

/**
 * User log out handler
 *
 * @param {Object} app current application
 * @param {Object} session current session object
 *
 */
var onUserLeave = function(app, session) {
	if(!session || !session.uid) {
		return;
	}
	app.rpc.chat.chatRemote.kick(session, session.uid, app.get('serverId'), session.get('rid'), null);
};